from sqlalchemy.orm import relationship

from exts import db
from datetime import datetime


# 用户借阅书籍中间表
tb_user_borrow = db.Table(
    'user_borrow',
    # 用户名
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
    # 书籍号
    db.Column('book_isbn', db.String(20), db.ForeignKey('books.bookisbn'), primary_key=True),
    db.Column('user_name', db.String(100), default="none"),
    # 借阅时间
    db.Column('borrowtime', db.DateTime, default=datetime.now),
    # 是否归还
    db.Column('isback', db.Integer, default=0)
)


class UserModel(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password = db.Column(db.String(200), nullable=False)
    permissions = db.Column(db.Integer, default=1)
    # 昵称
    nickname = db.Column(db.String(20))
    join_time = db.Column(db.DateTime, default=datetime.now)
    # 是否删除
    isdeleted = db.Column(db.Integer, default=1)
    # 学校
    school = db.Column(db.String(20))
    # 电话
    phone = db.Column(db.String(20))
    borrow = relationship('BookModel', backref="booklist", secondary=tb_user_borrow)



class BookModel(db.Model):
    __tablename__ = "books"
    # 书籍ISBN号-主键
    bookisbn = db.Column(db.String(20), primary_key=True)
    # 书名
    bookname = db.Column(db.String(40), nullable=False)
    # 书籍分类
    booktype = db.Column(db.Integer, nullable=False, default=0)
    # 作者
    author = db.Column(db.String(20), nullable=False, default="none")
    # 库存剩余
    remainder = db.Column(db.Integer, nullable=False, default=1)
    # 借出数量
    lend = db.Column(db.Integer, nullable=False, default=0)
    # 出版社名称
    printname = db.Column(db.String(20), nullable=False, default="none")
    # 出版时间
    printtime = db.Column(db.DateTime, default=datetime.now)
    # 是否删除
    isdeleted = db.Column(db.Integer, default=1)



class ClassifierModel(db.Model):
    __tablename__ = "classifier"
    # 校验码
    Checksum = db.Column(db.Integer, primary_key=True)
    # 分类名
    classname = db.Column(db.String(20), nullable=True, unique=True)






